package com.ruoyi.product.service.impl;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SpecGroupUtils;
import com.ruoyi.market.domain.dto.SkuCouponsCategoryDto;
import com.ruoyi.market.domain.dto.SkuCouponsDto;
import com.ruoyi.market.domain.vo.PageVo;
import com.ruoyi.market.domain.vo.PaginationVo;
import com.ruoyi.product.domain.ProductActivity;
import com.ruoyi.product.domain.ProductActivityGroup;
import com.ruoyi.product.domain.dto.*;
import com.ruoyi.product.domain.vo.Activity;
import com.ruoyi.product.domain.vo.Coupon;
import com.ruoyi.product.mapper.ProductActivityMapper;
import com.ruoyi.product.service.IProductActivityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 活动Service业务层处理
 *
 * @author liuhuizhong
 * @date 2025-08-13
 */
@Service
public class ProductActivityServiceImpl implements IProductActivityService {
    @Autowired
    private ProductActivityMapper productActivityMapper;

    /**
     * 查询活动
     *
     * @param activityId 活动主键
     * @return 活动
     */
    @Override
    public ProductActivity selectProductActivityByActivityId(Long activityId) {
        return productActivityMapper.selectProductActivityByActivityId(activityId);
    }

    /**
     * 查询活动列表
     *
     * @param productActivity 活动
     * @return 活动
     */
    @Override
    public List<ProductActivity> selectProductActivityList(ProductActivity productActivity) {
        return productActivityMapper.selectProductActivityList(productActivity);
    }

    /**
     * 新增活动
     *
     * @param productActivity 活动
     * @return 结果
     */
    @Override
    public int insertProductActivity(ProductActivity productActivity) {
        productActivity.setCreateTime(DateUtils.getNowDate());
        return productActivityMapper.insertProductActivity(productActivity);
    }

    /**
     * 修改活动
     *
     * @param productActivity 活动
     * @return 结果
     */
    @Override
    public int updateProductActivity(ProductActivity productActivity) {
        productActivity.setUpdateTime(DateUtils.getNowDate());
        return productActivityMapper.updateProductActivity(productActivity);
    }

    /**
     * 批量删除活动
     *
     * @param activityIds 需要删除的活动主键
     * @return 结果
     */
    @Override
    public int deleteProductActivityByActivityIds(Long[] activityIds) {
        return productActivityMapper.deleteProductActivityByActivityIds(activityIds);
    }

    /**
     * 删除活动信息
     *
     * @param activityId 活动主键
     * @return 结果
     */
    @Override
    public int deleteProductActivityByActivityId(Long activityId) {
        return productActivityMapper.deleteProductActivityByActivityId(activityId);
    }

    /**
     * 获取活动列表
     *
     * @param activityDto
     */
    @Override
    public List<ActivityDto> selectActivityList(ActivityDto activityDto) {
        List<ActivitySkuFlatDto> flatList = productActivityMapper.selectActivityList(activityDto);

        // 使用LinkedHashMap保持插入顺序
        Map<Long, ActivityDto> activityMap = new LinkedHashMap<>();

        for (ActivitySkuFlatDto item : flatList) {
            Long activityId = item.getActivityId();

            // 如果活动不存在，创建新的活动对象
            if (!activityMap.containsKey(activityId)) {
                ActivityDto activity = new ActivityDto();
                activity.setActivityId(item.getActivityId());
                activity.setActivityName(item.getActivityName());
                activity.setStartTime(item.getStartTime());
                activity.setEndTime(item.getEndTime());
                activity.setActivityDesc(item.getActivityDesc());
                activity.setPosterUrl(item.getPosterUrl());
                activity.setSkus(new ArrayList<>());
                activityMap.put(activityId, activity);
            }

            // 如果有SKU数据，添加到对应活动的SKU列表中
            if (item.getId() != null) {
                SkuDto sku = new SkuDto();
                sku.setId(item.getId());
                sku.setSpuId(item.getSpuId());
                sku.setCode(item.getCode());
                sku.setCategoryId(item.getCategoryId());
                sku.setSpecData(item.getSpecData());
                sku.setSpecValues(item.getSpecValues());
                sku.setPrice(item.getPrice());
                sku.setOriginalPrice(item.getOriginalPrice());
                sku.setCostPrice(item.getCostPrice());
                sku.setStock(item.getStock());
                sku.setLowStock(item.getLowStock());
                sku.setWeight(item.getWeight());
                sku.setVolume(item.getVolume());
                sku.setProductImages(item.getProductImages());
                sku.setStatus(item.getStatus());
                sku.setCreatedAt(item.getCreatedAt());
                sku.setUpdatedAt(item.getUpdatedAt());
                sku.setName(item.getName());
                sku.setLevel(item.getLevel());
                sku.setSpuName(item.getSpuName());
                sku.setSpuTitle(item.getSpuTitle());
                sku.setSpuDescription(item.getSpuDescription());
                sku.setUrl(item.getUrl());
                sku.setSpecNameGroup(item.getSpecNameGroupRaw());
                sku.setSpecValueGroup(item.getSpecValueGroupRaw());

                // 处理多个图片URL - 从数据库查询结果中的GROUP_CONCAT字符串转换为列表
                if (StringUtils.hasText(item.getUrls())) {
                    String[] urlArray = item.getUrls().split(",");
                    List<String> urlList = Arrays.stream(urlArray)
                            .map(String::trim)
                            .filter(url -> !url.isEmpty())
                            .collect(Collectors.toList());
                    sku.setUrls(urlList);
                } else if (StringUtils.hasText(item.getUrl())) {
                    // 如果urls为空但有单个url，则创建包含单个url的列表
                    sku.setUrls(Arrays.asList(item.getUrl()));
                }
                // 处理双斜杠
                item.setSpecNameGroup(SpecGroupUtils.processSpecNameGroup(item.getSpecNameGroupRaw()));
                item.setSpecValueGroup(SpecGroupUtils.processSpecValueGroup(item.getSpecValueGroupRaw()));

            }

        }

        return new ArrayList<>(activityMap.values());
    }

    /**
     * 根据活动id获取销量最高的前8个商品
     *
     * @param activityGroupId
     */
    @Override
    public List<SkuCouponsDto> saleTop8(Long activityGroupId) {
        List<SkuCouponsDto> rawResult = productActivityMapper.saleTop8(activityGroupId);

        if (rawResult == null || rawResult.isEmpty()) {
            return new ArrayList<>();
        }

        // 按skuId分组，合并相同skuId的urls
        Map<Long, SkuCouponsDto> skuMap = new LinkedHashMap<>();
        Map<Long, Set<String>> skuUrlsMap = new HashMap<>();
        Map<Long, List<Activity>> skuActivitiesMap = new HashMap<>();
        Map<Long, List<Coupon>> skuCouponsMap = new HashMap<>();

        for (SkuCouponsDto item : rawResult) {
            Long skuId = item.getSkuId();

            // 如果该skuId还没有处理过，创建新的对象
            if (!skuMap.containsKey(skuId)) {
                SkuCouponsDto mergedItem = new SkuCouponsDto();
                // 复制基本信息
                mergedItem.setSkuId(item.getSkuId());
                mergedItem.setSpuId(item.getSpuId());
                mergedItem.setCode(item.getCode());
                mergedItem.setCategoryId(item.getCategoryId());
                mergedItem.setSalesVolume(item.getSalesVolume());
                mergedItem.setSpecData(item.getSpecData());
                mergedItem.setPrice(item.getPrice());
                mergedItem.setOriginalPrice(item.getOriginalPrice());
                mergedItem.setStock(item.getStock());
                mergedItem.setLowStock(item.getLowStock());
                mergedItem.setWeight(item.getWeight());
                mergedItem.setVolume(item.getVolume());
                mergedItem.setStatus(item.getStatus());
                mergedItem.setSpecNameGroupRaw(item.getSpecNameGroupRaw());
                mergedItem.setSpecValueGroupRaw(item.getSpecValueGroupRaw());
                mergedItem.setCreatedAt(item.getCreatedAt());
                mergedItem.setUpdatedAt(item.getUpdatedAt());
                mergedItem.setSkuName(item.getSkuName());
                mergedItem.setDescription(item.getDescription());
                mergedItem.setCouponId(item.getCouponId());
                mergedItem.setActivityId(item.getActivityId());

                // 复制优惠券信息
                mergedItem.setCouponCode(item.getCouponCode());
                mergedItem.setCouponType(item.getCouponType());
                mergedItem.setCouponValue(item.getCouponValue());
                mergedItem.setCouponMinAmount(item.getCouponMinAmount());
                mergedItem.setCouponStartTime(item.getCouponStartTime());
                mergedItem.setCouponEndTime(item.getCouponEndTime());

                // 复制活动信息
                mergedItem.setActivityName(item.getActivityName());
                mergedItem.setActivityType(item.getActivityType());
                mergedItem.setActivityStatus(item.getActivityStatus());
                mergedItem.setActivityDescription(item.getActivityDescription());
                mergedItem.setActivityEndTime(item.getActivityEndTime());
                mergedItem.setActivityCreateTime(item.getActivityCreateTime());

                skuMap.put(skuId, mergedItem);
                skuUrlsMap.put(skuId, new HashSet<>());
                skuActivitiesMap.put(skuId, new ArrayList<>());
                skuCouponsMap.put(skuId, new ArrayList<>());
            }

            // 收集URLs
            if (item.getUrlRaw() != null && !item.getUrlRaw().trim().isEmpty()) {
                String[] urls = item.getUrlRaw().split(",");
                for (String url : urls) {
                    String trimmedUrl = url.trim();
                    if (!trimmedUrl.isEmpty()) {
                        skuUrlsMap.get(skuId).add(trimmedUrl);
                    }
                }
            }

            // 收集活动信息
            if (item.getActivityId() != null) {
                Activity activity = new Activity();
                activity.setActivityId(item.getActivityId());
                activity.setActivityName(item.getActivityName());
                activity.setActivityType(item.getActivityType());
                activity.setActivityStatus(item.getActivityStatus());
                activity.setActivityDescription(item.getActivityDescription());
                activity.setActivityEndTime(item.getActivityEndTime());
                activity.setActivityCreateTime(item.getActivityCreateTime());

                // 避免重复添加相同的活动
                List<Activity> activities = skuActivitiesMap.get(skuId);
                boolean exists = activities.stream()
                        .anyMatch(a -> a.getActivityId().equals(activity.getActivityId()));
                if (!exists) {
                    activities.add(activity);
                }
            }

            // 收集优惠券信息
            if (item.getCouponId() != null) {
                Coupon coupon = new Coupon();
                coupon.setCouponId(item.getCouponId());
                coupon.setCouponCode(item.getCouponCode());
                coupon.setCouponType(item.getCouponType());
                coupon.setCouponValue(item.getCouponValue());
                coupon.setCouponMinAmount(item.getCouponMinAmount());
                coupon.setCouponStartTime(item.getCouponStartTime());
                coupon.setCouponEndTime(item.getCouponEndTime());

                // 避免重复添加相同的优惠券
                List<Coupon> coupons = skuCouponsMap.get(skuId);
                boolean exists = coupons.stream()
                        .anyMatch(c -> c.getCouponId().equals(coupon.getCouponId()));
                if (!exists) {
                    coupons.add(coupon);
                }
            }
        }

        // 处理最终结果
        List<SkuCouponsDto> result = new ArrayList<>();
        for (SkuCouponsDto item : skuMap.values()) {
            Long skuId = item.getSkuId();

            // 设置合并后的URLs
            Set<String> urlSet = skuUrlsMap.get(skuId);
            if (!urlSet.isEmpty()) {
                item.setUrls(new ArrayList<>(urlSet));
            }

            // 处理规格组数据，去除双斜杠
            item.setSpecNameGroup(SpecGroupUtils.processSpecNameGroup(item.getSpecNameGroupRaw()));
            item.setSpecValueGroup(SpecGroupUtils.processSpecValueGroup(item.getSpecValueGroupRaw()));

            // 设置活动列表
            List<Activity> activities = skuActivitiesMap.get(skuId);
            if (!activities.isEmpty()) {
                item.setActivityList(activities);
            }

            // 设置优惠券列表
            List<Coupon> coupons = skuCouponsMap.get(skuId);
            if (!coupons.isEmpty()) {
                item.setCouponList(coupons);
            }

            result.add(item);
        }

        // 按销量降序排序，并只返回前8条数据
        result.sort((a, b) -> {
            Long salesA = a.getSalesVolume() != null ? a.getSalesVolume() : 0L;
            Long salesB = b.getSalesVolume() != null ? b.getSalesVolume() : 0L;
            return salesB.compareTo(salesA); // 降序排序
        });

        // 限制为前8条数据
        if (result.size() > 8) {
            result = result.subList(0, 8);
        }

        return result;
    }

    /**
     * 根据活动id获取销量最高的商品（支持分页，返回分页信息）
     *
     * @param activityGroupId 活动组ID
     * @param pagination      分页信息
     * @return 包含数据和分页信息的响应对象
     */
    @Override
    public ActivitySaleTopResponseDto saleTop8WithPagination(Long activityGroupId, PaginationVo pagination) {
        // 先获取所有数据（不分页）来计算总数
        List<SkuCouponsDto> allData = saleTop8(activityGroupId);

        // 计算总数
        long total = allData.size();

        // 应用分页
        List<SkuCouponsDto> pagedData;
        if (pagination != null && pagination.getPageNum() != null && pagination.getPageSize() != null) {
            int pageNum = pagination.getPageNum();
            int pageSize = pagination.getPageSize();
            int startIndex = (pageNum - 1) * pageSize;
            int endIndex = Math.min(startIndex + pageSize, allData.size());

            if (startIndex < allData.size()) {
                pagedData = allData.subList(startIndex, endIndex);
            } else {
                pagedData = new ArrayList<>();
            }
        } else {
            pagedData = allData;
        }

        // 创建分页信息
        PageVo pageVo = new PageVo();
        pageVo.setTotal(total);
        pageVo.setPageNum(
                pagination != null && pagination.getPageNum() != null ? pagination.getPageNum().longValue() : 1L);
        pageVo.setPageSize(pagination != null && pagination.getPageSize() != null ? pagination.getPageSize().longValue()
                : (long) pagedData.size());

        // 创建响应对象
        ActivitySaleTopResponseDto response = new ActivitySaleTopResponseDto();
        response.setData(pagedData);
        response.setPagination(pageVo);

        return response;
    }

    /**
     * 根据活动id获取分类商品列表
     *
     * @param activityGroupId
     */
    @Override
    public List<SkuCouponsCategoryDto> getActivityCategoryList(Long activityGroupId) {
        // 获取原始数据
        List<SkuCouponsCategoryDto> rawData = productActivityMapper.getActivityCategoryList(activityGroupId);

        // 按categoryId和categoryName分组
        Map<String, List<SkuCouponsCategoryDto>> groupedData = rawData.stream()
                .collect(Collectors.groupingBy(item -> item.getCategoryId() + "_" + item.getCategoryName()));

        List<SkuCouponsCategoryDto> result = new ArrayList<>();

        for (Map.Entry<String, List<SkuCouponsCategoryDto>> entry : groupedData.entrySet()) {
            List<SkuCouponsCategoryDto> categoryItems = entry.getValue();
            if (categoryItems.isEmpty())
                continue;

            // 创建分类DTO
            SkuCouponsCategoryDto categoryDto = new SkuCouponsCategoryDto();
            SkuCouponsCategoryDto firstItem = categoryItems.get(0);
            categoryDto.setCategoryId(firstItem.getCategoryId());
            categoryDto.setCategoryName(firstItem.getCategoryName());

            // 按skuId分组，构建SKU列表
            Map<Long, List<SkuCouponsCategoryDto>> skuGroups = categoryItems.stream()
                    .collect(Collectors.groupingBy(SkuCouponsCategoryDto::getSkuId));

            // 用于收集每个SKU的URLs
            Map<Long, Set<String>> skuUrlsMap = new HashMap<>();
            Map<Long, List<Activity>> skuActivitiesMap = new HashMap<>();
            Map<Long, List<Coupon>> skuCouponsMap = new HashMap<>();

            List<SkuCouponsDto> skuList = new ArrayList<>();
            for (Map.Entry<Long, List<SkuCouponsCategoryDto>> skuEntry : skuGroups.entrySet()) {
                List<SkuCouponsCategoryDto> skuItems = skuEntry.getValue();
                if (skuItems.isEmpty())
                    continue;

                SkuCouponsCategoryDto firstSkuItem = skuItems.get(0);
                Long skuId = firstSkuItem.getSkuId();

                // 初始化收集器
                skuUrlsMap.put(skuId, new HashSet<>());
                skuActivitiesMap.put(skuId, new ArrayList<>());
                skuCouponsMap.put(skuId, new ArrayList<>());

                // 构建SKU DTO
                SkuCouponsDto skuDto = new SkuCouponsDto();
                skuDto.setSkuId(firstSkuItem.getSkuId());
                skuDto.setSpuId(firstSkuItem.getSpuId());
                skuDto.setCode(firstSkuItem.getCode());
                skuDto.setCategoryId(String.valueOf(firstSkuItem.getCategoryId()));
                skuDto.setSpecData(firstSkuItem.getSpecData());
                skuDto.setPrice(firstSkuItem.getPrice());
                skuDto.setOriginalPrice(firstSkuItem.getOriginalPrice());
                skuDto.setSkuName(firstSkuItem.getSkuName());
                skuDto.setDescription(firstSkuItem.getDescription());
                skuDto.setStock(firstSkuItem.getStock());
                skuDto.setSalesVolume(firstSkuItem.getSalesVolume());
                skuDto.setLowStock(firstSkuItem.getLowStock());
                skuDto.setWeight(firstSkuItem.getWeight());
                skuDto.setVolume(firstSkuItem.getVolume());
                skuDto.setStatus(firstSkuItem.getStatus() != null ? firstSkuItem.getStatus().longValue() : null);
                skuDto.setCreatedAt(firstSkuItem.getCreatedAt());
                skuDto.setUpdatedAt(firstSkuItem.getUpdatedAt());
                skuDto.setUrlRaw(firstSkuItem.getUrlRaw());

                // 处理规格组数据，使用SpecGroupUtils处理
                skuDto.setSpecNameGroup(SpecGroupUtils.processSpecNameGroup(firstSkuItem.getSpecNameGroupRaw()));
                skuDto.setSpecValueGroup(SpecGroupUtils.processSpecValueGroup(firstSkuItem.getSpecValueGroupRaw()));

                // 收集URLs、活动和优惠券信息
                for (SkuCouponsCategoryDto item : skuItems) {
                    // 收集URLs
                    if (item.getUrlRaw() != null && !item.getUrlRaw().trim().isEmpty()) {
                        String[] urls = item.getUrlRaw().split(",");
                        for (String url : urls) {
                            String trimmedUrl = url.trim();
                            if (!trimmedUrl.isEmpty()) {
                                skuUrlsMap.get(skuId).add(trimmedUrl);
                            }
                        }
                    }

                    // 收集活动信息
                    if (item.getActivityId() != null) {
                        Activity activity = new Activity();
                        activity.setActivityId(item.getActivityId());
                        activity.setActivityName(item.getActivityName());
                        activity.setActivityType(
                                item.getActivityType() != null ? item.getActivityType().longValue() : null);
                        activity.setActivityStatus(
                                item.getActivityStatus() != null ? item.getActivityStatus().longValue() : null);
                        activity.setActivityDescription(item.getActivityDescription());
                        activity.setActivityEndTime(item.getActivityEndTime());
                        activity.setActivityCreateTime(item.getActivityCreateTime());

                        // 避免重复添加相同的活动
                        List<Activity> activities = skuActivitiesMap.get(skuId);
                        boolean exists = activities.stream()
                                .anyMatch(a -> a.getActivityId().equals(activity.getActivityId()));
                        if (!exists) {
                            activities.add(activity);
                        }
                    }

                    // 收集优惠券信息
                    if (item.getCouponId() != null) {
                        Coupon coupon = new Coupon();
                        coupon.setCouponId(item.getCouponId());
                        coupon.setCouponCode(item.getCouponCode());
                        coupon.setCouponType(item.getCouponType() != null ? item.getCouponType().longValue() : null);
                        coupon.setCouponValue(
                                item.getCouponValue() != null ? item.getCouponValue().doubleValue() : null);
                        coupon.setCouponMinAmount(
                                item.getCouponMinAmount() != null ? item.getCouponMinAmount().doubleValue() : null);
                        coupon.setCouponStartTime(
                                item.getCouponStartTime() != null ? item.getCouponStartTime().toString() : null);
                        coupon.setCouponEndTime(
                                item.getCouponEndTime() != null ? item.getCouponEndTime().toString() : null);

                        // 避免重复添加相同的优惠券
                        List<Coupon> coupons = skuCouponsMap.get(skuId);
                        boolean exists = coupons.stream()
                                .anyMatch(c -> c.getCouponId().equals(coupon.getCouponId()));
                        if (!exists) {
                            coupons.add(coupon);
                        }
                    }
                }

                // 设置合并后的URLs
                Set<String> urlSet = skuUrlsMap.get(skuId);
                if (!urlSet.isEmpty()) {
                    skuDto.setUrls(new ArrayList<>(urlSet));
                }

                // 设置活动列表
                List<Activity> activities = skuActivitiesMap.get(skuId);
                if (!activities.isEmpty()) {
                    skuDto.setActivityList(activities);
                }

                // 设置优惠券列表
                List<Coupon> coupons = skuCouponsMap.get(skuId);
                if (!coupons.isEmpty()) {
                    skuDto.setCouponList(coupons);
                }

                skuList.add(skuDto);
            }

            categoryDto.setSkus(skuList);

            // 设置分页信息（这里可以根据需要设置）
            List<PageVo> pagination = new ArrayList<>();
            PageVo pageVo = new PageVo();
            pageVo.setTotal((long) skuList.size());
            pageVo.setPageNum(1L);
            pageVo.setPageSize(8L);
            pagination.add(pageVo);
            categoryDto.setPagination(pagination);

            result.add(categoryDto);
        }

        return result;
    }

    /**
     * 根据分类id和活动id获取不同页数的商品记录
     *
     * @param request 请求参数，包含活动ID、分类ID和分页信息
     */
    @Override
    public List<SkuCouponsCategoryDto> getActivityCategoryListPage(SkuActivityCategoryRequestDto request) {
        // 计算offset值
        if (request.getPagination() != null && request.getPagination().getPageNum() != null
                && request.getPagination().getPageSize() != null) {
            int offset = (request.getPagination().getPageNum() - 1) * request.getPagination().getPageSize();
            request.setOffset(offset);
        }

        // 获取原始数据
        List<SkuCouponsCategoryDto> rawData = productActivityMapper.getActivityCategoryListPage(request);

        // 按categoryId和categoryName分组
        Map<String, List<SkuCouponsCategoryDto>> groupedData = rawData.stream()
                .collect(Collectors.groupingBy(item -> item.getCategoryId() + "_" + item.getCategoryName()));

        List<SkuCouponsCategoryDto> result = new ArrayList<>();

        for (Map.Entry<String, List<SkuCouponsCategoryDto>> entry : groupedData.entrySet()) {
            List<SkuCouponsCategoryDto> categoryItems = entry.getValue();
            if (categoryItems.isEmpty())
                continue;

            // 创建分类DTO
            SkuCouponsCategoryDto categoryDto = new SkuCouponsCategoryDto();
            SkuCouponsCategoryDto firstItem = categoryItems.get(0);
            categoryDto.setCategoryId(firstItem.getCategoryId());
            categoryDto.setCategoryName(firstItem.getCategoryName());

            // 按skuId分组，构建SKU列表
            Map<Long, List<SkuCouponsCategoryDto>> skuGroups = categoryItems.stream()
                    .collect(Collectors.groupingBy(SkuCouponsCategoryDto::getSkuId));

            // 用于收集每个SKU的URLs
            Map<Long, Set<String>> skuUrlsMap = new HashMap<>();
            Map<Long, List<Activity>> skuActivitiesMap = new HashMap<>();
            Map<Long, List<Coupon>> skuCouponsMap = new HashMap<>();

            List<SkuCouponsDto> skuList = new ArrayList<>();
            for (Map.Entry<Long, List<SkuCouponsCategoryDto>> skuEntry : skuGroups.entrySet()) {
                List<SkuCouponsCategoryDto> skuItems = skuEntry.getValue();
                if (skuItems.isEmpty())
                    continue;

                SkuCouponsCategoryDto firstSkuItem = skuItems.get(0);
                Long skuId = firstSkuItem.getSkuId();

                // 初始化收集器
                skuUrlsMap.put(skuId, new HashSet<>());
                skuActivitiesMap.put(skuId, new ArrayList<>());
                skuCouponsMap.put(skuId, new ArrayList<>());

                // 构建SKU DTO
                SkuCouponsDto skuDto = new SkuCouponsDto();
                skuDto.setSkuId(firstSkuItem.getSkuId());
                skuDto.setSpuId(firstSkuItem.getSpuId());
                skuDto.setCode(firstSkuItem.getCode());
                skuDto.setCategoryId(String.valueOf(firstSkuItem.getCategoryId()));
                skuDto.setSpecData(firstSkuItem.getSpecData());
                skuDto.setPrice(firstSkuItem.getPrice());
                skuDto.setOriginalPrice(firstSkuItem.getOriginalPrice());
                skuDto.setSkuName(firstSkuItem.getSkuName());
                skuDto.setDescription(firstSkuItem.getDescription());
                skuDto.setStock(firstSkuItem.getStock());
                skuDto.setSalesVolume(firstSkuItem.getSalesVolume());
                skuDto.setLowStock(firstSkuItem.getLowStock());
                skuDto.setWeight(firstSkuItem.getWeight());
                skuDto.setVolume(firstSkuItem.getVolume());
                skuDto.setStatus(firstSkuItem.getStatus() != null ? firstSkuItem.getStatus().longValue() : null);
                skuDto.setCreatedAt(firstSkuItem.getCreatedAt());
                skuDto.setUpdatedAt(firstSkuItem.getUpdatedAt());
                skuDto.setUrlRaw(firstSkuItem.getUrlRaw());

                // 处理规格组数据，使用SpecGroupUtils处理
                skuDto.setSpecNameGroup(SpecGroupUtils.processSpecNameGroup(firstSkuItem.getSpecNameGroupRaw()));
                skuDto.setSpecValueGroup(SpecGroupUtils.processSpecValueGroup(firstSkuItem.getSpecValueGroupRaw()));

                // 收集URLs、活动和优惠券信息
                for (SkuCouponsCategoryDto item : skuItems) {
                    // 收集URLs
                    if (item.getUrlRaw() != null && !item.getUrlRaw().trim().isEmpty()) {
                        String[] urls = item.getUrlRaw().split(",");
                        for (String url : urls) {
                            String trimmedUrl = url.trim();
                            if (!trimmedUrl.isEmpty()) {
                                skuUrlsMap.get(skuId).add(trimmedUrl);
                            }
                        }
                    }

                    // 收集活动信息
                    if (item.getActivityId() != null) {
                        Activity activity = new Activity();
                        activity.setActivityId(item.getActivityId());
                        activity.setActivityName(item.getActivityName());
                        activity.setActivityType(
                                item.getActivityType() != null ? item.getActivityType().longValue() : null);
                        activity.setActivityStatus(
                                item.getActivityStatus() != null ? item.getActivityStatus().longValue() : null);
                        activity.setActivityDescription(item.getActivityDescription());
                        activity.setActivityEndTime(item.getActivityEndTime());
                        activity.setActivityCreateTime(item.getActivityCreateTime());

                        // 避免重复添加相同的活动
                        List<Activity> activities = skuActivitiesMap.get(skuId);
                        boolean exists = activities.stream()
                                .anyMatch(a -> a.getActivityId().equals(activity.getActivityId()));
                        if (!exists) {
                            activities.add(activity);
                        }
                    }

                    // 收集优惠券信息
                    if (item.getCouponId() != null) {
                        Coupon coupon = new Coupon();
                        coupon.setCouponId(item.getCouponId());
                        coupon.setCouponCode(item.getCouponCode());
                        coupon.setCouponType(item.getCouponType() != null ? item.getCouponType().longValue() : null);
                        coupon.setCouponValue(
                                item.getCouponValue() != null ? item.getCouponValue().doubleValue() : null);
                        coupon.setCouponMinAmount(
                                item.getCouponMinAmount() != null ? item.getCouponMinAmount().doubleValue() : null);
                        coupon.setCouponStartTime(
                                item.getCouponStartTime() != null ? item.getCouponStartTime().toString() : null);
                        coupon.setCouponEndTime(
                                item.getCouponEndTime() != null ? item.getCouponEndTime().toString() : null);

                        // 避免重复添加相同的优惠券
                        List<Coupon> coupons = skuCouponsMap.get(skuId);
                        boolean exists = coupons.stream()
                                .anyMatch(c -> c.getCouponId().equals(coupon.getCouponId()));
                        if (!exists) {
                            coupons.add(coupon);
                        }
                    }
                }

                // 设置合并后的URLs
                Set<String> urlSet = skuUrlsMap.get(skuId);
                if (!urlSet.isEmpty()) {
                    skuDto.setUrls(new ArrayList<>(urlSet));
                }

                // 设置活动列表
                List<Activity> activities = skuActivitiesMap.get(skuId);
                if (!activities.isEmpty()) {
                    skuDto.setActivityList(activities);
                }

                // 设置优惠券列表
                List<Coupon> coupons = skuCouponsMap.get(skuId);
                if (!coupons.isEmpty()) {
                    skuDto.setCouponList(coupons);
                }

                skuList.add(skuDto);
            }

            categoryDto.setSkus(skuList);

            // 设置分页信息
            List<PageVo> pagination = new ArrayList<>();
            PageVo pageVo = new PageVo();
            pageVo.setTotal((long) skuList.size());
            pageVo.setPageNum(request.getPagination() != null ? request.getPagination().getPageNum().longValue() : 1L);
            pageVo.setPageSize(
                    request.getPagination() != null ? request.getPagination().getPageSize().longValue() : 8L);
            pagination.add(pageVo);
            categoryDto.setPagination(pagination);

            result.add(categoryDto);
        }

        return result;
    }

    /**
     * 获取所有活动
     */
    @Override
    public List<ProductActivityGroup> getAllActivity() {
        List<ProductActivityGroup> result = productActivityMapper.getAllActivity();
        return result;
    }

    /**
     * 获取所有活动销量最高的前8个商品
     */
    @Override
    public List<SkuCouponsDto> getAllActivitySaleTop8() {
        List<SkuCouponsDto> rawResult = productActivityMapper.getAllActivitySaleTop8();

        if (rawResult == null || rawResult.isEmpty()) {
            return new ArrayList<>();
        }

        // 按skuId分组，合并相同skuId的urls
        Map<Long, SkuCouponsDto> skuMap = new LinkedHashMap<>();
        Map<Long, Set<String>> skuUrlsMap = new HashMap<>();
        Map<Long, List<Activity>> skuActivitiesMap = new HashMap<>();
        Map<Long, List<Coupon>> skuCouponsMap = new HashMap<>();

        for (SkuCouponsDto item : rawResult) {
            Long skuId = item.getSkuId();

            // 如果该skuId还没有处理过，创建新的对象
            if (!skuMap.containsKey(skuId)) {
                SkuCouponsDto mergedItem = new SkuCouponsDto();
                // 复制基本信息
                mergedItem.setSkuId(item.getSkuId());
                mergedItem.setSpuId(item.getSpuId());
                mergedItem.setCode(item.getCode());
                mergedItem.setCategoryId(item.getCategoryId());
                mergedItem.setSalesVolume(item.getSalesVolume());
                mergedItem.setSpecData(item.getSpecData());
                mergedItem.setPrice(item.getPrice());
                mergedItem.setOriginalPrice(item.getOriginalPrice());
                mergedItem.setStock(item.getStock());
                mergedItem.setLowStock(item.getLowStock());
                mergedItem.setWeight(item.getWeight());
                mergedItem.setVolume(item.getVolume());
                mergedItem.setStatus(item.getStatus());
                mergedItem.setSpecNameGroupRaw(item.getSpecNameGroupRaw());
                mergedItem.setSpecValueGroupRaw(item.getSpecValueGroupRaw());
                mergedItem.setCreatedAt(item.getCreatedAt());
                mergedItem.setUpdatedAt(item.getUpdatedAt());
                mergedItem.setSkuName(item.getSkuName());
                mergedItem.setDescription(item.getDescription());
                mergedItem.setCouponId(item.getCouponId());
                mergedItem.setActivityId(item.getActivityId());

                // 复制优惠券信息
                mergedItem.setCouponCode(item.getCouponCode());
                mergedItem.setCouponType(item.getCouponType());
                mergedItem.setCouponValue(item.getCouponValue());
                mergedItem.setCouponMinAmount(item.getCouponMinAmount());
                mergedItem.setCouponStartTime(item.getCouponStartTime());
                mergedItem.setCouponEndTime(item.getCouponEndTime());

                // 复制活动信息
                mergedItem.setActivityName(item.getActivityName());
                mergedItem.setActivityType(item.getActivityType());
                mergedItem.setActivityStatus(item.getActivityStatus());
                mergedItem.setActivityDescription(item.getActivityDescription());
                mergedItem.setActivityEndTime(item.getActivityEndTime());
                mergedItem.setActivityCreateTime(item.getActivityCreateTime());

                skuMap.put(skuId, mergedItem);
                skuUrlsMap.put(skuId, new HashSet<>());
                skuActivitiesMap.put(skuId, new ArrayList<>());
                skuCouponsMap.put(skuId, new ArrayList<>());
            }

            // 收集URLs
            if (item.getUrlRaw() != null && !item.getUrlRaw().trim().isEmpty()) {
                String[] urls = item.getUrlRaw().split(",");
                for (String url : urls) {
                    String trimmedUrl = url.trim();
                    if (!trimmedUrl.isEmpty()) {
                        skuUrlsMap.get(skuId).add(trimmedUrl);
                    }
                }
            }

            // 收集活动信息
            if (item.getActivityId() != null) {
                Activity activity = new Activity();
                activity.setActivityId(item.getActivityId());
                activity.setActivityName(item.getActivityName());
                activity.setActivityType(item.getActivityType());
                activity.setActivityStatus(item.getActivityStatus());
                activity.setActivityDescription(item.getActivityDescription());
                activity.setActivityEndTime(item.getActivityEndTime());
                activity.setActivityCreateTime(item.getActivityCreateTime());

                // 避免重复添加相同的活动
                List<Activity> activities = skuActivitiesMap.get(skuId);
                boolean exists = activities.stream()
                        .anyMatch(a -> a.getActivityId().equals(activity.getActivityId()));
                if (!exists) {
                    activities.add(activity);
                }
            }

            // 收集优惠券信息
            if (item.getCouponId() != null) {
                Coupon coupon = new Coupon();
                coupon.setCouponId(item.getCouponId());
                coupon.setCouponCode(item.getCouponCode());
                coupon.setCouponType(item.getCouponType());
                coupon.setCouponValue(item.getCouponValue());
                coupon.setCouponMinAmount(item.getCouponMinAmount());
                coupon.setCouponStartTime(item.getCouponStartTime());
                coupon.setCouponEndTime(item.getCouponEndTime());

                // 避免重复添加相同的优惠券
                List<Coupon> coupons = skuCouponsMap.get(skuId);
                boolean exists = coupons.stream()
                        .anyMatch(c -> c.getCouponId().equals(coupon.getCouponId()));
                if (!exists) {
                    coupons.add(coupon);
                }
            }
        }

        // 处理最终结果
        List<SkuCouponsDto> result = new ArrayList<>();
        for (SkuCouponsDto item : skuMap.values()) {
            Long skuId = item.getSkuId();

            // 设置合并后的URLs
            Set<String> urlSet = skuUrlsMap.get(skuId);
            if (!urlSet.isEmpty()) {
                item.setUrls(new ArrayList<>(urlSet));
            }

            // 处理规格组数据，去除双斜杠
            item.setSpecNameGroup(SpecGroupUtils.processSpecNameGroup(item.getSpecNameGroupRaw()));
            item.setSpecValueGroup(SpecGroupUtils.processSpecValueGroup(item.getSpecValueGroupRaw()));

            // 设置活动列表
            List<Activity> activities = skuActivitiesMap.get(skuId);
            if (!activities.isEmpty()) {
                item.setActivityList(activities);
            }

            // 设置优惠券列表
            List<Coupon> coupons = skuCouponsMap.get(skuId);
            if (!coupons.isEmpty()) {
                item.setCouponList(coupons);
            }

            result.add(item);
        }

        // 按销量降序排序，并只返回前8条数据
        result.sort((a, b) -> {
            Long salesA = a.getSalesVolume() != null ? a.getSalesVolume() : 0L;
            Long salesB = b.getSalesVolume() != null ? b.getSalesVolume() : 0L;
            return salesB.compareTo(salesA); // 降序排序
        });

        // 限制为前8条数据
        if (result.size() > 8) {
            result = result.subList(0, 8);
        }

        return result;
    }

    /**
     * 获取所有活动销量最高的商品（支持分页，返回分页信息）
     *
     * @param pagination 分页信息
     * @return 包含数据和分页信息的响应对象
     */
    @Override
    public AllActivitySaleTopResponseDto getAllActivitySaleTop8WithPagination(PaginationVo pagination) {
        // 先获取所有数据（不分页）来计算总数
        List<SkuCouponsDto> allData = getAllActivitySaleTop8();

        // 计算总数
        long total = allData.size();

        // 应用分页
        List<SkuCouponsDto> pagedData;
        if (pagination != null && pagination.getPageNum() != null && pagination.getPageSize() != null) {
            int pageNum = pagination.getPageNum();
            int pageSize = pagination.getPageSize();
            int startIndex = (pageNum - 1) * pageSize;
            int endIndex = Math.min(startIndex + pageSize, allData.size());

            if (startIndex < allData.size()) {
                pagedData = allData.subList(startIndex, endIndex);
            } else {
                pagedData = new ArrayList<>();
            }
        } else {
            pagedData = allData;
        }

        // 创建分页信息
        PageVo pageVo = new PageVo();
        pageVo.setTotal(total);
        pageVo.setPageNum(
                pagination != null && pagination.getPageNum() != null ? pagination.getPageNum().longValue() : 1L);
        pageVo.setPageSize(pagination != null && pagination.getPageSize() != null ? pagination.getPageSize().longValue()
                : (long) pagedData.size());

        // 创建响应对象
        AllActivitySaleTopResponseDto response = new AllActivitySaleTopResponseDto();
        response.setData(pagedData);
        response.setPagination(pageVo);

        return response;
    }

    /**
     * 获取所有活动分类商品列表
     *
     * @return 活动分类商品列表
     */
    @Override
    public List<SkuActivityCategoriesDto> getAllActivityCategorySkus() {
        // 获取原始数据
        List<SkuActivityCategoriesDto> rawData = productActivityMapper.getAllActivityCategorySkus();

        // 过滤掉无效数据
        List<SkuActivityCategoriesDto> filteredData = rawData.stream()
                .filter(item -> item.getActivityGroupId() != null
                        && item.getActivityGroupName() != null
                        && !item.getActivityGroupName().trim().isEmpty()
                        && item.getSkuId() != null)
                .collect(Collectors.toList());

        // 按activityGroupId和activityGroupName分组
        Map<String, List<SkuActivityCategoriesDto>> groupedData = filteredData.stream()
                .collect(Collectors.groupingBy(item -> item.getActivityGroupId() + "_" + item.getActivityGroupName()));

        List<SkuActivityCategoriesDto> result = new ArrayList<>();

        for (Map.Entry<String, List<SkuActivityCategoriesDto>> entry : groupedData.entrySet()) {
            List<SkuActivityCategoriesDto> categoryItems = entry.getValue();
            if (categoryItems.isEmpty())
                continue;

            // 创建分类DTO
            SkuActivityCategoriesDto categoryDto = new SkuActivityCategoriesDto();
            SkuActivityCategoriesDto firstItem = categoryItems.get(0);
            categoryDto.setActivityGroupId(firstItem.getActivityGroupId());
            categoryDto.setActivityGroupName(firstItem.getActivityGroupName());

            // 按skuId分组，构建SKU列表
            Map<Long, List<SkuActivityCategoriesDto>> skuGroups = categoryItems.stream()
                    .collect(Collectors.groupingBy(SkuActivityCategoriesDto::getSkuId));

            List<SkuActivityDto> skuList = new ArrayList<>();
            for (Map.Entry<Long, List<SkuActivityCategoriesDto>> skuEntry : skuGroups.entrySet()) {
                List<SkuActivityCategoriesDto> skuItems = skuEntry.getValue();
                if (skuItems.isEmpty())
                    continue;

                // 创建SKU DTO
                SkuActivityDto skuDto = new SkuActivityDto();
                SkuActivityCategoriesDto firstSkuItem = skuItems.get(0);

                // 设置SKU基本信息
                skuDto.setSkuId(firstSkuItem.getSkuId());
                skuDto.setSpuId(firstSkuItem.getSpuId());
                skuDto.setCode(firstSkuItem.getCode());
                skuDto.setSpecData(firstSkuItem.getSpecData());
                skuDto.setPrice(firstSkuItem.getPrice());
                skuDto.setOriginalPrice(firstSkuItem.getOriginalPrice());
                skuDto.setSkuName(firstSkuItem.getSkuName());
                skuDto.setDescription(firstSkuItem.getDescription());
                skuDto.setStock(firstSkuItem.getStock());
                skuDto.setSalesVolume(firstSkuItem.getSalesVolume());
                skuDto.setLowStock(firstSkuItem.getLowStock());
                skuDto.setWeight(firstSkuItem.getWeight());
                skuDto.setVolume(firstSkuItem.getVolume());
                skuDto.setStatus(firstSkuItem.getStatus());
                skuDto.setCreatedAt(firstSkuItem.getCreatedAt());
                skuDto.setUpdatedAt(firstSkuItem.getUpdatedAt());

                // 处理规格组数据
                if (StringUtils.hasText(firstSkuItem.getSpecNameGroupRaw())) {
                    skuDto.setSpecNameGroup(SpecGroupUtils.processSpecNameGroup(firstSkuItem.getSpecNameGroupRaw()));
                }
                if (StringUtils.hasText(firstSkuItem.getSpecValueGroupRaw())) {
                    skuDto.setSpecValueGroup(SpecGroupUtils.processSpecValueGroup(firstSkuItem.getSpecValueGroupRaw()));
                }

                // 收集URLs
                Set<String> urls = new HashSet<>();
                for (SkuActivityCategoriesDto item : skuItems) {
                    if (StringUtils.hasText(item.getUrlRaw())) {
                        urls.add(item.getUrlRaw());
                    }
                }
                skuDto.setUrls(new ArrayList<>(urls));

                // 构建优惠券列表
                List<Coupon> couponList = new ArrayList<>();
                for (SkuActivityCategoriesDto item : skuItems) {
                    if (item.getCouponId() != null) {
                        Coupon coupon = new Coupon();
                        coupon.setId(item.getCouponId());
                        coupon.setCode(item.getCouponCode());
                        coupon.setName(item.getCouponName());
                        coupon.setType(item.getCouponType().longValue());
                        coupon.setValue(item.getCouponValue().doubleValue());
                        coupon.setMinAmount(item.getCouponMinAmount().doubleValue());
                        coupon.setCouponStock(item.getCouponStock());
                        coupon.setStartTime(item.getCouponStartTime());
                        coupon.setEndTime(item.getCouponEndTime());
                        coupon.setGetTime(item.getGetTime());
                        coupon.setStatus(item.getCouponStatus().longValue());
                        coupon.setRemark(item.getCouponRemark());
                        coupon.setCouponGroupId(item.getCouponGroupId());
                        coupon.setUseOrderId(item.getUseOrderId());
                        coupon.setUserId(item.getUserId());
                        couponList.add(coupon);
                    }
                }
                skuDto.setCouponList(couponList);

                // 构建活动列表
                List<Activity> activityList = new ArrayList<>();
                for (SkuActivityCategoriesDto item : skuItems) {
                    if (item.getActivityId() != null) {
                        Activity activity = new Activity();
                        activity.setActivityId(item.getActivityId());
                        activity.setActivityName(item.getActivityName());
                        activity.setActivityType(item.getActivityType().longValue());
                        activity.setActivityStatus(item.getActivityStatus().longValue());
                        activity.setActivityDescription(item.getActivityDescription());
                        activity.setActivityEndTime(item.getActivityEndTime());
                        activity.setActivityCreateTime(item.getActivityCreateTime());
                        activity.setStartTime(item.getActivityStartTime());
                        activity.setEndTime(item.getActivityEndTime());
                        activity.setPosterUrl(item.getPosterUrl());
                        activityList.add(activity);
                    }
                }
                skuDto.setActivityList(activityList);

                skuList.add(skuDto);
            }

            categoryDto.setSkus(skuList);

            // 设置分页信息
            PageVo pagination = new PageVo();
            pagination.setTotal((long) skuList.size());
            pagination.setPageSize(8L);
            pagination.setPageNum(1L);
            categoryDto.setPagination(pagination);

            result.add(categoryDto);
        }

        // 按activityGroupId从低到高排序
        result.sort(Comparator.comparing(SkuActivityCategoriesDto::getActivityGroupId));

        return result;
    }

    /**
     * 根据活动id获取不同页数的商品记录
     *
     * @param request 请求参数，包含活动ID和分页信息
     */
    @Override
    public List<SkuCouponsCategoryDto> getActivityPage(ActivityPageRequestDto request) {
        // 计算offset值
        if (request.getPagination() != null && request.getPagination().getPageNum() != null
                && request.getPagination().getPageSize() != null) {
            int offset = (request.getPagination().getPageNum() - 1) * request.getPagination().getPageSize();
            request.setOffset(offset);
        }

        // 获取原始数据
        List<SkuCouponsCategoryDto> rawData = productActivityMapper.getActivityPage(request);

        // 按categoryId和categoryName分组
        Map<String, List<SkuCouponsCategoryDto>> groupedData = rawData.stream()
                .collect(Collectors.groupingBy(item -> item.getCategoryId() + "_" + item.getCategoryName()));

        List<SkuCouponsCategoryDto> result = new ArrayList<>();

        for (Map.Entry<String, List<SkuCouponsCategoryDto>> entry : groupedData.entrySet()) {
            List<SkuCouponsCategoryDto> categoryItems = entry.getValue();
            if (categoryItems.isEmpty())
                continue;

            // 创建分类DTO
            SkuCouponsCategoryDto categoryDto = new SkuCouponsCategoryDto();
            SkuCouponsCategoryDto firstItem = categoryItems.get(0);
            categoryDto.setCategoryId(firstItem.getCategoryId());
            categoryDto.setCategoryName(firstItem.getCategoryName());

            // 按skuId分组，构建SKU列表
            Map<Long, List<SkuCouponsCategoryDto>> skuGroups = categoryItems.stream()
                    .collect(Collectors.groupingBy(SkuCouponsCategoryDto::getSkuId));

            // 用于收集每个SKU的URLs
            Map<Long, Set<String>> skuUrlsMap = new HashMap<>();
            Map<Long, List<Activity>> skuActivitiesMap = new HashMap<>();
            Map<Long, List<Coupon>> skuCouponsMap = new HashMap<>();

            List<SkuCouponsDto> skuList = new ArrayList<>();
            for (Map.Entry<Long, List<SkuCouponsCategoryDto>> skuEntry : skuGroups.entrySet()) {
                List<SkuCouponsCategoryDto> skuItems = skuEntry.getValue();
                if (skuItems.isEmpty())
                    continue;

                SkuCouponsCategoryDto firstSkuItem = skuItems.get(0);
                Long skuId = firstSkuItem.getSkuId();

                // 初始化收集器
                skuUrlsMap.put(skuId, new HashSet<>());
                skuActivitiesMap.put(skuId, new ArrayList<>());
                skuCouponsMap.put(skuId, new ArrayList<>());

                // 构建SKU DTO
                SkuCouponsDto skuDto = new SkuCouponsDto();
                skuDto.setSkuId(firstSkuItem.getSkuId());
                skuDto.setSpuId(firstSkuItem.getSpuId());
                skuDto.setCode(firstSkuItem.getCode());
                skuDto.setCategoryId(String.valueOf(firstSkuItem.getCategoryId()));
                skuDto.setSpecData(firstSkuItem.getSpecData());
                skuDto.setPrice(firstSkuItem.getPrice());
                skuDto.setOriginalPrice(firstSkuItem.getOriginalPrice());
                skuDto.setSkuName(firstSkuItem.getSkuName());
                skuDto.setDescription(firstSkuItem.getDescription());
                skuDto.setStock(firstSkuItem.getStock());
                skuDto.setSalesVolume(firstSkuItem.getSalesVolume());
                skuDto.setLowStock(firstSkuItem.getLowStock());
                skuDto.setWeight(firstSkuItem.getWeight());
                skuDto.setVolume(firstSkuItem.getVolume());
                skuDto.setStatus(firstSkuItem.getStatus() != null ? firstSkuItem.getStatus().longValue() : null);
                skuDto.setCreatedAt(firstSkuItem.getCreatedAt());
                skuDto.setUpdatedAt(firstSkuItem.getUpdatedAt());
                skuDto.setUrlRaw(firstSkuItem.getUrlRaw());

                // 处理规格组数据，使用SpecGroupUtils处理
                skuDto.setSpecNameGroup(SpecGroupUtils.processSpecNameGroup(firstSkuItem.getSpecNameGroupRaw()));
                skuDto.setSpecValueGroup(SpecGroupUtils.processSpecValueGroup(firstSkuItem.getSpecValueGroupRaw()));

                // 收集URLs、活动和优惠券信息
                for (SkuCouponsCategoryDto item : skuItems) {
                    // 收集URLs
                    if (item.getUrlRaw() != null && !item.getUrlRaw().trim().isEmpty()) {
                        String[] urls = item.getUrlRaw().split(",");
                        for (String url : urls) {
                            String trimmedUrl = url.trim();
                            if (!trimmedUrl.isEmpty()) {
                                skuUrlsMap.get(skuId).add(trimmedUrl);
                            }
                        }
                    }

                    // 收集活动信息
                    if (item.getActivityId() != null) {
                        Activity activity = new Activity();
                        activity.setActivityId(item.getActivityId());
                        activity.setActivityName(item.getActivityName());
                        activity.setActivityType(
                                item.getActivityType() != null ? item.getActivityType().longValue() : null);
                        activity.setActivityStatus(
                                item.getActivityStatus() != null ? item.getActivityStatus().longValue() : null);
                        activity.setActivityDescription(item.getActivityDescription());
                        activity.setActivityEndTime(item.getActivityEndTime());
                        activity.setActivityCreateTime(item.getActivityCreateTime());

                        // 避免重复添加相同的活动
                        List<Activity> activities = skuActivitiesMap.get(skuId);
                        boolean exists = activities.stream()
                                .anyMatch(a -> a.getActivityId().equals(activity.getActivityId()));
                        if (!exists) {
                            activities.add(activity);
                        }
                    }

                    // 收集优惠券信息
                    if (item.getCouponId() != null) {
                        Coupon coupon = new Coupon();
                        coupon.setCouponId(item.getCouponId());
                        coupon.setCouponCode(item.getCouponCode());
                        coupon.setCouponType(item.getCouponType() != null ? item.getCouponType().longValue() : null);
                        coupon.setCouponValue(
                                item.getCouponValue() != null ? item.getCouponValue().doubleValue() : null);
                        coupon.setCouponMinAmount(
                                item.getCouponMinAmount() != null ? item.getCouponMinAmount().doubleValue() : null);
                        coupon.setCouponStartTime(
                                item.getCouponStartTime() != null ? item.getCouponStartTime().toString() : null);
                        coupon.setCouponEndTime(
                                item.getCouponEndTime() != null ? item.getCouponEndTime().toString() : null);

                        // 避免重复添加相同的优惠券
                        List<Coupon> coupons = skuCouponsMap.get(skuId);
                        boolean exists = coupons.stream()
                                .anyMatch(c -> c.getCouponId().equals(coupon.getCouponId()));
                        if (!exists) {
                            coupons.add(coupon);
                        }
                    }
                }

                // 设置合并后的URLs
                Set<String> urlSet = skuUrlsMap.get(skuId);
                if (!urlSet.isEmpty()) {
                    skuDto.setUrls(new ArrayList<>(urlSet));
                }

                // 设置活动列表
                List<Activity> activities = skuActivitiesMap.get(skuId);
                if (!activities.isEmpty()) {
                    skuDto.setActivityList(activities);
                }

                // 设置优惠券列表
                List<Coupon> coupons = skuCouponsMap.get(skuId);
                if (!coupons.isEmpty()) {
                    skuDto.setCouponList(coupons);
                }

                skuList.add(skuDto);
            }

            categoryDto.setSkus(skuList);

            // 设置分页信息
            List<PageVo> pagination = new ArrayList<>();
            PageVo pageVo = new PageVo();
            pageVo.setTotal((long) skuList.size());
            pageVo.setPageNum(request.getPagination() != null ? request.getPagination().getPageNum().longValue() : 1L);
            pageVo.setPageSize(
                    request.getPagination() != null ? request.getPagination().getPageSize().longValue() : 8L);
            pagination.add(pageVo);
            categoryDto.setPagination(pagination);

            result.add(categoryDto);
        }

        return result;
    }
}
